package com.bytedance.improvingroad.binder.server

import android.R
import android.os.Binder
import android.os.IBinder
import android.os.Parcel
import android.os.RemoteException
import com.bytedance.improvingroad.binder.Book
import com.bytedance.improvingroad.binder.proxy.Proxy


/**
 * Created by chenxiong
 * date 12/14/21
 */
abstract class Stub: Binder(), BookManager {

    companion object {
        const val TRANSAVTION_getBooks = FIRST_CALL_TRANSACTION
        const val TRANSAVTION_addBook = FIRST_CALL_TRANSACTION + 1
        private const val DESCRIPTOR = "com.bytedance.improvingroad.binder.server.BookManager"

        fun asInterface(binder: IBinder?): BookManager? {
            if (binder == null) {
                return null
            }
            val iin = binder.queryLocalInterface(DESCRIPTOR)
            if (iin != null && iin is BookManager) {
                return iin
            }
            return Proxy(binder)
        }
    }

    override fun asBinder(): IBinder {
        return this
    }

    @Throws(RemoteException::class)
    override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {
        when (code) {
            INTERFACE_TRANSACTION -> {
                reply?.writeString(DESCRIPTOR)
                return true
            }
            TRANSAVTION_getBooks -> {
                data.enforceInterface(DESCRIPTOR)
                val result = getBooks()
                reply!!.writeNoException()
                reply.writeTypedList(result)
                return true
            }
            TRANSAVTION_addBook -> {
                data.enforceInterface(DESCRIPTOR)
                var arg0: Book? = null
                if (data.readInt() != 0) {
                    arg0 = Book.CREATOR.createFromParcel(data)
                }
                if (arg0 != null) {
                    addBook(arg0)
                }
                reply?.writeNoException()
                return true
            }
        }
        return super.onTransact(code, data, reply, flags)
    }

}